import './swiper.scss'
import common from '../BaseComponent/index.js'
class Swiper extends common {
    constructor(options) {
        super(options)
        const defaultOptions = {
            direction: 'horizontal', // 方向
            type: 'comment',
            position: 'bottom',// 位置
            threshold: 50, // 开端起点
            interval: 5000, //间隔
            duration: 500, // 持续时间
            isShow: true, // 是否显示
            data: [],
            mode: 'dark',
            text: '详情',
            url:'',
            callback: () => { }
        }
        this.options = Object.assign(defaultOptions, options)
        this._start = {}
        this._move = {}
        this._end = {}
        this._prev = 0
        this._current = 1
        this._offset = 0
        this._goto = -1
        this._width = 0;
        this._height = 0;
        this.$container = "";
        this.$items = [];  // 最后复制完后的数据，放在这里
        this.$dots = [];  
        this.datas = this.options.data.filter((item) => {
            return item.img && item.text  // 过滤掉 没有图片或内容的数据
        })
        this.options.isShow = this.datas.length > 0  // 确保有数据
        this._count = this.datas.length > 5 ? 7 : this.datas.length + 2;
        // 将inintSwiper 函数绑定到全局， 为了之后此函数能在其他函数中调用，且一定要写到 那个函数调用之前
        // 如 在_initDiv() 中调用 _inintSwiper ，则 this._inintSwiper = this.inintSwiper 要写在 this. _initDiv()之前
        this._initDiv()
        this._bindEvent()
    }
    
//  创元素 添加元素 设置某些动态元素的属性值
    _initDiv() { 
        let $box = this.options.container   //获取Element 信息  
        this.$container = this.createDiv('swiper')  // swiper盒子
        this.$dots = this.createDiv('swiper-dots') // dot 盒子
        let datas = this.datas.length > 5 ? this.datas.slice(0, 5) : this.datas;
        let $firstItem = null
        let $endItem = null
        // 遍历，并创建
        let imgClass = ''

            //如果是评论类型， 则 图片是圆形   不是评论类型，则是方形
        if (this.options.type === 'comment') {
            imgClass = 'swiper-img-avator-circle'
        }
        else { 
            imgClass='swiper-img-avator'
        }
        let textMode = ''
        let swiperMode = ''
        
            // 模式选择
        if (this.options.mode === 'dark') {
            textMode = 'swiper-text-dark'
            $box.classList.add('swiper-dark')
        } else { 
            textMode = 'swiper-text-light'
            $box.classList.add('swiper-light')
        }
        
        
        this.datas.forEach((item, index) => {
            let $item = this.createDiv('swiper-item')
            const $img = this.createImg(imgClass,item.img)
            const $text = this.createDiv(textMode,item.text)
            const $button = this.createDiv('swiper-button',this.options.text)
            $button.addEventListener('click', () => 
            {
                    this.options.callback.call(this,index)
                    this.jump(item.url)
            })
            let $fragments = document.createDocumentFragment()
            
            $fragments.appendChild($text)
            $fragments.appendChild($img)
            $fragments.appendChild($button)
            $item.appendChild($fragments)
            this.$container.appendChild($item)
            if (index == 0 && datas.length > 1) { 
               $firstItem = this.createDiv('swiper-item')
               const $img = this.createImg(imgClass,item.img)
                const $text = this.createDiv(textMode,item.text)
              const  $button = this.createDiv('swiper-button',this.options.text)
                $button.addEventListener('click', () => { 
                    this.options.callback.call(this,index)
                    this.jump(item.url)
                    console.log('你点击了我，我是打开按钮');
                })
              let  $fragments = document.createDocumentFragment()
                $fragments.appendChild($img)
                $fragments.appendChild($text)
                $fragments.appendChild($button)
                $firstItem.appendChild($fragments)
            }
            if (index == datas.length - 1 && datas.length > 1) { 
                $endItem = this.createDiv('swiper-item')
                const  $img = this.createImg(imgClass,item.img)
                const $text = this.createDiv(textMode,item.text)
                const $button = this.createDiv('swiper-button',this.options.text)
                $button.addEventListener('click', () => { 
                    this.options.callback.call(this,index)
                    this.jump(item.url)
                })
               let $fragments = document.createDocumentFragment()
                $fragments.appendChild($img)
                $fragments.appendChild($text)
                $fragments.appendChild($button)
                $endItem.appendChild($fragments)
            }
        })
        // 将复制好的 第一个 和最后一个，分别放到最后一个和第一个
        if (datas.length > 1) { 
            let $second = this.$container.childNodes[0]
            this.$container.insertBefore($endItem, $second)
            this.$container.appendChild($firstItem)
        }
        //获取所有的 swiper-item
        this.$items = this.$container.querySelectorAll('.swiper-item')


        // 判断位置  如果是 top则不加dot，如果是bottom，则添加dot
        if (this.options.position === 'top') {
            $box.classList.add('swiper-top')
            $box.appendChild(this.$container)
        }
        else { 
            $box.classList.add('swiper-bottom')
            $box.appendChild(this.$container)
            if (this.datas.length > 1) { 
                let $fragmentDot = this.createCountDiv('swiper-dots-item',null,this._count - 2)
                this.$dots.appendChild($fragmentDot)
                $box.appendChild(this.$dots)
                //获取所有的dots
                this.$dots=document.querySelectorAll('.swiper-dots-item')  
            }
        }
        // 得到swiper这个盒子的大小
        var swiper_width = this.$container.offsetWidth
        this._width = swiper_width
        var swiper_height = this.$container.offsetHeight
        this._height =swiper_height
        
        //给响应的swiper—item 和父亲本来宽高一样
        this.$items.forEach((item) => {
            item.style.width = swiper_width + 'px'
            item.style.height =swiper_height +'px'
        })
        // 之后根据 swiper-item的多少，来进行计算新的父亲长度
        var swiper_allWidth = swiper_width * this._count
        this.$container.style.width = swiper_allWidth + 'px'

        //初始化轮播图
        this.inintSwiper(0)
    }
//  绑定事件 
    _bindEvent() {

        var that = this
        // 开始触摸
        this.$container.addEventListener(
            'touchstart',
            function (e) {
                clearInterval(that._timeout)
                that._timeout = null
              /*    touch事件中有三个 属性
                touches : 绑定事件的那个结点上的触摸点的集合列表
                targetTouches:  绑定事件的那个结点上的触摸点的集合列表
                changedTouches:  触发事件时改变的触摸点的集合
         */
                that._start.x = e.changedTouches[0].pageX
                that._start.y = e.changedTouches[0].pageY
                // 兼容
                that.$container.style["-webkit-transition"] = "none"
                that.$container.style.transition="none"
            }
        )
        // 移动
        this.$container.addEventListener('touchmove', function (e) { 
            that._move.x = e.changedTouches[0].pageX
            that._move.y = e.changedTouches[0].pageY
            var distance = 0
            var transform = ''
                distance = that._move.x - that._start.x;
                // 计算移动的距离
                transform = "translate3d(" +(distance - that._offset)   + "px,0,0)"
            
            // 兼容 其他浏览器
            that.$container.style["-webkit-transform"] = transform  
            // 进行移动
            that.$container.style.transform=transform
            
        })
        // 移动结束
        this.$container.addEventListener(
            'touchend',
            function (e) { 
           
                that._end.x = e.changedTouches[0].pageX
                that._end.y = e.changedTouches[0].pageY
                var distance = 0
                // 计算移动距离
             
                    distance = that._end.x - that._start.x;
             
                    // 记录此刻的索引
                that._prev = that._current
                // 右滑，当距离大于 规定门槛， 则 小圆点-1
                if (distance > that.options.threshold) {
                    that._current = that._current === 0 ? 0 : --that._current;
                }

                //  左滑， 大于规定门槛， 则  圆点 +1
                else if (distance < -that.options.threshold) { 
                   
             that._current =  that._current < that._count - 1 ? ++that._current : that._current
                }
                // 不懂

                that._show(that._current)
                     // 开启新定时器
                    that._openTimer()
            
            }
        )
    }

// 初始化轮播
    inintSwiper(index) { 
            // 对小点的，排他思想
        if (this.options.position == "bottom" && this.datas.length > 1) { 
            this.$dots.forEach((item,key) => { 
                item.classList.remove("swiper-dot-active")
                if (index === key) { 
                    item.classList.add('swiper-dot-active')
                }
            })
        }
        if (this.datas.length > 1) { 
            var transform = '' 
         
                this._offset = 1 * this._width
                // 切记一定要加上px
                transform = "translate3d(-" + this._offset + "px,0,0)"
            var duration ="0ms"
            this.$container.style.transform = transform
            this.$container.style.transition = duration
        }
        this._openTimer()
    }
//显示
    _show(index) { 
        var transform = ''
            this._offset = index * this._width
            transform= `translate3d(-${this._offset}px,0,0)`
        var duration = this.options.duration + 'ms'
        this.$container.style.transform = transform
        this.$container.style.transition = duration
        // 当index 到达边界的时候和没有到达边界时，对圆点的设置
        if (this.options.position == "bottom" && this.datas.length > 1) { 
            var num = index - 1
            // index到达了边界，则对num重新设置
            if (index == 0) {
                num = this._count - 3
            }
            if (index == this._count - 1) { 
                num = 0
            }
            this.$dots.forEach((item, key) => { 
                item.classList.remove('swiper-dot-active')
                if (num == key) { 
                    item.classList.add('swiper-dot-active')
                }
            })
        }
        setTimeout(() => {
            if (index == this._count - 1) { 
                this._current = 1
                this._quickMove(1)
            }
            if (index == 0) { 
                this._current = this._count - 2
                this._quickMove(this._count - 2)
            }
        }, 500);
        // 此刻的时间，应该和过渡的时间一致，比如此刻正在过渡到最后一个，然后设置个定时器，当过渡完的瞬间，跳到1（索引）

    }
// 实现无缝连接
    _quickMove(index) { 
        var duration = "0ms"
        this._offset = index * this._width
        var transform = `translate3d(-${this._offset}px,0,0)`
        this.$container.style.transform = transform
        this.$container.style.transition = duration
    }
// 切换至下一个
    next() { 
        this._prev = this._current
        this._show(++this._current)
        return 
    }
// 自动播放
    _openTimer() { 
        clearInterval(this._timeout)
        if (this.datas.length > 1) { 
            this._timeout =setInterval(() => {
                this.next()
            }, this.options.interval);
        }
    }


}
export default  Swiper